<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\jeek\shop\SkuGoods;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\BrowseLog;
use app\common\model\Category;
use app\common\model\Coupon;
use app\common\model\Couponlog;
use app\common\model\Follow;
use app\common\model\Project as ProjectModel;
use app\common\model\UserAnswers;
use app\common\model\UserVip;
use fast\Random;
use tencent\api\Im;
use think\Config;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($captcha != 8888) {
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            $openid_is = !$user->app_openid ? 0 : 1;
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $openid_is = 0;
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');

            $im = new Im();
            $chk_add_im = $im->check_bind($this->auth->tencent_account);
            if (empty($chk_add_im)) {
                $im->account_import($this->auth->tencent_account, $this->auth->nickname, cdnurl($this->auth->avatar, true));
            }

            $data = ['userinfo' => $this->auth->getUserinfo(),'openid_is' => $openid_is];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * Account:保存微信APPopenid
     * User: Ixiangang
     * Date: 2025/5/23
     * Time: 17:32
     */
    public function weChatOpenid()
    {
        $user_id = $this->auth->id;
        $app_openid = $this->request->post('app_openid');
        if (!$app_openid) {
            $this->error("参数错误");
        }
        $user = \app\admin\model\User::get($user_id);
        if (empty($user)) {
            $this->error("用户信息查询不到");
        }
        $user->app_openid = $app_openid;
        $row = $user->save();
        if ($row) {
            $this->success("成功");
        }
        $this->error("失败");
    }


    /**
     * Account:新增赠送优惠卷
     * User: Ixiangang
     * Date: 2025/1/2
     *
     * Time: 13:29
     */
    public function newcoupon(Request $request, Coupon $coupon, Couponlog $couponlog)
    {
        $user_id = $this->auth->id;
        $type = $request->post('type'); //1=优惠卷展示，2=领取优惠卷
        if (!in_array($type, [1, 2])) {
            $this->error(__('参数错误'));
        }
        if ($type == 1) {
            $list = Coupon::where('type', 1)->where('deletetime IS NULL')->select();
            $this->success(__("OK"), $list);
        }
        if ($type == 2) {
            $coupon_id = $request->post('coupon_id');
            if (!$coupon_id) {
                $this->error(__('缺少优惠卷coupon_id'));
            }
            $couponInfo = $coupon->where('id', $coupon_id)->find();
            if (empty($couponInfo)) {
                $this->error(__('优惠卷不存在'));
            }
            $day = $couponInfo->day;
            $data = [
                'coupon_id' => $couponInfo->id,
                'user_id' => $user_id,
                'use_for' => 1,
                'upstage' => 0, //1代表后台发放
                'issuance_time' => time(),  //发放时间
                'expiration' => strtotime("+$day days", time()), //根据有优惠券天数算优惠券到期时间
                'status' => $couponInfo->status,
                'coupon_price' => $couponInfo->fullminus,
                'man_price' => $couponInfo->satisfynum,
                'createtime' => time(),
            ];
            $rs = \app\common\model\Couponlog::create($data);
            if ($rs) {
                $this->success(__("OK"));
            }
            $this->error(__("NO"));
        }
    }

    /**
     * Account:我的优惠卷
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 14:52
     */
    public function couponUserList()
    {
        $user_id = $this->auth->id;
        $order_money = $this->request->post('order_money', ''); //满减金额
        $use_for = $this->request->post('use_for', ''); //1=待使用,2=已使用,3=已过期
        $list = (new Couponlog())->getList(['user_id' => $user_id, 'use_for' => $use_for], $order_money);
        $this->success(__("OK"), $list);
    }


    /**
     * Account:个人中心
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 14:50
     */
    public function person()
    {
        $user = $this->auth->getUser();
        # 查询咨询师
        $goods = SkuGoods::where('user_id', $this->auth->id)->find();
        if (!empty($goods)) {
            $user->goodsIs = 1; // 已入住
            $user->goods_examine = $goods->examine; //1=待审核,2=通过,3=拒绝
        } else {
            $user->goodsIs = 0; //咨询师未认证
        }
        # 查询是否是合伙人
        $copartner = \app\common\model\Copartner::where('user_id', $user->id)->find();
        if (!empty($copartner)) {
            $user->copartnerIs = 1; //已申请
            $user->ispay = $copartner->ispay; //1=入驻成功,0=未缴费
        } else {
            $user->copartnerIs = 0; //未入驻合伙人
            $user->ispay = '-1'; //用于前段判断
        }
        # 我关注咨询师数量
        $user->followCount = Follow::where('user_id', $user->id)->count();


        # 测评题目
        $project_ids = UserAnswers::where(['user_id' => $user->id])->group('project_id')->column('project_id');
        $project_count = ProjectModel::field("id,name,image")->where('id', 'in', $project_ids)->count();
        # 咨询师+测评项目 浏览数量
        $user->browseCount = BrowseLog::where('user_id', $user->id)->count() + $project_count; //浏览数量  咨询师+测评项目 浏览数量

        # 是否领取过新人优惠卷
        $coupon_ids = Coupon::where('type', 1)->column('id');
        $couponlogIs = Couponlog::where('coupon_id', 'in', $coupon_ids)->where('user_id', $user->id)->find();
        $user->couponlogIs = !empty($couponlogIs) ? 1 : 0;

        # 合伙人金额
        $user->pay_copartner = \config('site.pay_copartner');
        $this->success("OK", $user);
    }

    /**
     * Account:腾讯聊天
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 14:00
     */
    public function getUserSig($type)
    {
        #  1=用户 2=咨询师
        if (!in_array($type, [1, 2])) {
            $this->error("参数错误");
        }
        $im = new Im();
        # 用户
        if ($type == 1) {
            $user = $this->auth->getUser();
            # 获取签名
            $usersign = $im->genUserSig($user->tencent_account);
        }
        # 咨询师
        if ($type == 2) {
            $tencent_account = SkuGoods::where('user_id', $this->auth->id)->value('tencent_account');
            if (empty($tencent_account)) {
                $this->error("咨询师不存在");
            }
            $usersign = $im->genUserSig($tencent_account);
        }
        $this->success("OK", ['type' => $type, 'usersign' => $usersign]);
    }

    /**
     * Account:用户修改个人信息
     * User: Ixiangang
     * Date: 2025/2/11
     * Time: 18:59
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender', 0); //性别:0=男，1=女
        $avatar = $this->request->post('avatar', '');
        $profileitem = [];
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('用户昵称重复'));
            }
            $user->nickname = $nickname;
            $itemarr['Tag'] = "Tag_Profile_IM_Nick";
            $itemarr['Value'] = $nickname;
            $profileitem[] = $itemarr;
        }
        if ($avatar) {
            $user->avatar = $avatar;
            $itemarr['Tag'] = "Tag_Profile_IM_Image";
            $itemarr['Value'] = cdnurl($avatar,true);
            $profileitem[] = $itemarr;
        }
        $user->gender = $gender;
        $user->updatetime = time();
        $user->save();
        # 修改资料
        $im = new Im();
        $im->set_info($user['tencent_account'], $profileitem);
        $this->success();
    }

    /**
     * Account:升级vip
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 15:07
     */
    public function vip()
    {
        $user = $this->auth->getUser();
        if ($user->vip == 1) {
            $this->error("您已经是永久VIP");
        }
        $pay_type = $this->request->get('pay_type');
        if (!in_array($pay_type, ['wechat', 'alipay'])) {
            $this->error('传参不正确');
        }
        if ($pay_type == "wechat") {
            if (!$this->auth->app_openid) $this->error('请先绑定微信');
        }
        $data = [
            'order_sn' => 'V_' . date('YmdHis') . rand(1111, 9999),
            'user_id' => $user->id,
            'pay_price' => config('site.vip_price'),
            'pay_type' => $pay_type,
            'createtime' => time(),
        ];
        $row = UserVip::create($data);
        if ($row) {
            $params = [
                'amount' => $data['pay_price'],
                'orderid' => $data['order_sn'],
                'type' => $pay_type,
                'title' => "升级VIP",
                'notifyurl' =>$this->request->root(true) . '/api/pay/notify/paytype/' . $pay_type,
                'method' => 'app',
                'openid' => $this->auth->app_openid,
            ];
            $pay = Service::submitOrder($params);
            $this->success('支付成功', compact('pay', 'pay_type'));
        }
        $this->error("支付错误");
    }


    /**
     * Account:绑定微信账户
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 15:11
     */
    public function bangWechat()
    {
        $user = $this->auth->getUser();
        $wechat_account = $this->request->post('wechat_account');
        $wechat_name = $this->request->post('wechat_name');
        if (!$wechat_account || !$wechat_name) {
            $this->error("微信账号您称不能为空");
        }
        $user->wechat_account = $wechat_account;
        $user->wechat_name = $wechat_name;
        $user->updatetime = time();
        $user->save();
        $this->success("绑定成功");
    }

    /**
     * 注册会员
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }


    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
